package com.bw.common.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bw.common.domain.SysMenu;
import com.bw.common.domain.SysRoleMenu;
import com.bw.common.service.SysMenuService;
import com.bw.common.service.SysRoleMenuService;
import com.bw.common.service.SysRoleService;
import com.ruoyi.common.core.domain.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("roleMenu")
public class RoleMenuController {
    @Autowired
    SysMenuService menuService;
    @Autowired
    SysRoleService roleService;
    @Autowired
    SysRoleMenuService roleMenuService;

    @RequestMapping("menuList")
    public R menuList(){
        List<SysMenu> list = menuService.list();
        //        转树形结构
        List<SysMenu> menus=new ArrayList<>();
        for (SysMenu sysMenu : list) {
            if (sysMenu.getParentId()==0){
                menus.add(sysMenu);
            }else {
                if (menus!=null){
                    for (SysMenu menu : menus) {
                        if (menu.getId()==sysMenu.getParentId()){
                            if (menu.getChildren() == null) {
                                menu.setChildren(new ArrayList<SysMenu>());
                            }
                            menu.getChildren().add(sysMenu);
                        }
                    }
                }else {
                    menus.add(sysMenu);
                }
            }
        }
        System.err.println(menus);
        return R.ok(menus);
    }


    @RequestMapping("menuRoleList")
    public R menuRoleList(String id){
//      查询该角色的menu的数据
        List<SysMenu> list=menuService.menuList(id);
        return R.ok(list);
    }

    @RequestMapping("addRoleMenu")
    @Transactional
    public R addRoleMenu(String id,String mid){
        if (id.isEmpty()||mid.isEmpty()){
            return R.fail("更改失败");
        }else {
            LambdaQueryWrapper<SysRoleMenu> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SysRoleMenu::getRoleId,id);
            roleMenuService.remove(wrapper);
            String[] split = mid.split(",");
            for (String s : split) {
                SysRoleMenu menu = new SysRoleMenu();
                menu.setMenuId(Integer.valueOf(s));
                menu.setRoleId(Integer.valueOf(id));
                roleMenuService.save(menu);
            }
            return R.ok("更改成功");
        }
    }
}
